#include "limittextedit.h"
#include "ui_limittextedit.h"

LimitTextEdit::LimitTextEdit(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::LimitTextEdit)
{
    ui->setupUi(this);

    connect(ui->textEdit, &QTextEdit::textChanged,
            this, &LimitTextEdit::slot_handleInput);
}

LimitTextEdit::~LimitTextEdit()
{
    delete ui;
}

QString LimitTextEdit::content()
{
    return ui->textEdit->document()->toPlainText();
}

void LimitTextEdit::setMaxWordNum(const int maxNum)
{
    m_maxWordNum = maxNum;
    ui->labelMaxNum->setNum(m_maxWordNum);
}

void LimitTextEdit::setTitle(const QString &title)
{
    ui->labelTitle->setText(title);
}

void LimitTextEdit::setContent(const QString &content)
{
    ui->textEdit->setText(content);

    QTextDocument* doc = ui->textEdit->document();

    for(QTextBlock it = doc->begin(); it != doc->end(); it = it.next())
    {
        QTextCursor textCursor(it);
        QTextBlockFormat textBlockFormat = it.blockFormat();
        textBlockFormat.setLineHeight(24,QTextBlockFormat::FixedHeight);  //set line height
        textCursor.setBlockFormat(textBlockFormat);
        ui->textEdit->setTextCursor(textCursor);
    }
    // 将光标移回起始点
    ui->textEdit->setTextCursor(QTextCursor(doc->begin()));
}

void LimitTextEdit::slot_handleInput()
{
    auto textEdit = static_cast<QTextEdit*>(sender());

    int currentNum = textEdit->toPlainText().length();
    // 判断是不是超出了字数限制
    if (currentNum > m_maxWordNum) {
        QString text = textEdit->toPlainText();
        text = text.mid(0, m_maxWordNum);
        int position = textEdit->textCursor().position();

        textEdit->setText(text);
        QTextCursor cursor = textEdit->textCursor();
        if (position > m_maxWordNum) {
            // 如果当前输入位置为末尾的话，就直接跳到最后一个字符。
            position = m_maxWordNum;
        }
        cursor.setPosition(position);
        textEdit->setTextCursor(cursor);
        currentNum = m_maxWordNum;
    }

    ui->labelCurrentNum->setNum(currentNum);
}
